<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\api\controller\Testsand;
use app\common\controller\Backend;
use think\Db;
use app\admin\model\CouponCodeCategory;


/**
 * 库存预警管理
 *
 * @icon fa fa-circle-o
 */
class StockWarning extends Backend
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = CouponCodeCategory::where($where)
                ->where('is_enable', 1)
                ->count();
            $list = CouponCodeCategory::where($where)
                ->order($sort, $order)
                ->where('is_enable', 1)
                ->limit($offset, $limit)
                ->field('id,name,warning_num,warning_mobile,code_marking,brand_id')
                ->select();
            if ($total > 0) { //微信券码库存
                foreach ($list as $key => $value) {
                    if ($value['code_marking']) {
                        $brand_code = User::where('id', $value['brand_id'])->value('brand_code');
                        $couponCount = Testsand::couponCount($value['code_marking'],$brand_code);
                        if ($couponCount['code'] == 200 && $couponCount['content']) {
                            $max_coupons = $couponCount['content']['stock_use_rule']['max_coupons']; //代金券数量
                            $distributed_coupons = $couponCount['content']['distributed_coupons']; //已发放代金券数量
                            $list[$key]['stock'] = $max_coupons - $distributed_coupons;
                        }
                    }
                    $list[$key]['brand_name'] = User::where('id', $value['brand_id'])->value('username');
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = CouponCodeCategory::get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
//        print_r($row);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
